package fr.upmc.mdoc.tp1.servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;
import org.hibernate.Transaction;

import fr.upmc.mdoc.tp1.models.ContactGroup;
import fr.upmc.mdoc.tp1.tools.HibernateUtil;

/**
 * Servlet implementation class Login
 */
public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		System.out.println("Login/doPost/session.save(groupe)");
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		ContactGroup g = new ContactGroup();
		g.setGroupName("Amis");
		session.save(g);
		g = new ContactGroup();
		g.setGroupName("Collègues");
		session.save(g);
		g = new ContactGroup();
		g.setGroupName("Famille");
		session.save(g);
		tx.commit();

		// fermeture de la session
		// session.close();

		String user = request.getParameter("user");
		String pass = request.getParameter("pass");

		if (user.length() == 0 && pass.length() == 0)
			request.getRequestDispatcher("pages/erreur.jsp").forward(request,
					response);
		else
			request.getRequestDispatcher(
					(!user.equals(pass)) ? "./" : "pages/accueil.jsp").forward(
					request, response);
		
		mapping.findForward("/Connect.do");
		
		return super.execute(mapping, form, request, response);
	}
	
}
